package com.health.mapp.service;

import com.alibaba.fastjson.JSONObject;
import com.wxtools.api.IService;
import com.wxtools.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JsapiTicketServer extends HttpServlet{

    @Autowired
    private IService mpService;

    public void init(ServletConfig config) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        JSONObject object=null;
        try {
            String jsapiTicket=mpService.getJsapiTicket();
            object=new JSONObject();
            object.put("errorCode",0);
            object.put("errorMsg","success");
            object.put("jsapi_ticket",jsapiTicket);
        } catch (WxErrorException e) {
            e.printStackTrace();
            object=new JSONObject();
            object.put("errorCode",-1);
            object.put("errorMsg",e.getMessage());
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter out = response.getWriter();
        out.print(object.toJSONString());
        out.println("\r\n");
        out.flush();
        out.close();
    }

    public IService getMpService() {
        return mpService;
    }

    public void setMpService(IService mpService) {
        this.mpService = mpService;
    }
}
